package handler

import (
	"2212b/happy_orange/api/handler/request"
	"2212b/happy_orange/consts"
	"2212b/happy_orange/internal/dao"
	"2212b/happy_orange/internal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func Login(c *gin.Context) {
	var req request.LoginReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id == 0 {
		user = model.User{
			Mobile:   req.Mobile,
			Password: req.Password,
		}
		dao.Create(&model.User{})
	} else {
		if user.Password != req.Password {
			c.JSON(http.StatusOK, gin.H{
				"code": 100000,
				"msg":  "账号或密码失败",
				"data": nil,
			})
			return
		}
	}
	token, err := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().UnixMilli() + 3600*24,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "生成token失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "成功",
		"data": token,
	})

}

func GetUserList(c *gin.Context) {

}
